package com.example.demo;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

// MainActivity.java
public class ViewPagerFragmentTest extends AppCompatActivity {

    private ViewPager2 viewPager;
    private TabLayout tabLayout;
    private FragmentAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager_fragment_test);

        initView();
        setupViewPager();
        setupTabLayout();
    }

    private void initView() {
        viewPager = findViewById(R.id.viewPagerFragmentVp);
        tabLayout = findViewById(R.id.tabLayout);
    }

    private void setupViewPager() {
        // 创建Adapter
        adapter = new FragmentAdapter(this);
        viewPager.setAdapter(adapter);

        // 设置预加载页面数量（提升性能）
        viewPager.setOffscreenPageLimit(adapter.getItemCount());

        // 页面切换监听
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                String pageName = adapter.getTitle(position);
                Log.d("ViewPager", "切换到: " + pageName);

                // 显示当前页面Toast
                Toast.makeText(ViewPagerFragmentTest.this, pageName, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupTabLayout() {
        // 关联TabLayout和ViewPager
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            // 设置Tab的文本
            tab.setText(adapter.getTitle(position));
        }).attach();

        // Tab点击监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.d("Tab", "选中: " + tab.getText());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // Tab取消选中
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 再次点击当前Tab
                Log.d("Tab", "重新选中: " + tab.getText());
            }
        });
    }
}